let http = require('http')
let path = require('path')
let fs = require('fs').promises
let url = require('url')
let {
    createReadStream,
    createWriteStream,
    readFileSync
} = require('fs')
let mime = require('mime')
let chalk = require('chalk')
let nunjucks = require('nunjucks')


let EventEmitter = require('events')

templateStr = path.resolve(__dirname, "t.html")


module.exports = class Serve extends EventEmitter {
    //http://localhost:3000/public/index.html

    constructor(config) {
        super()
        this.port = config.port || 3000
        this.dir = process.cwd()
        //将模板的实例挂载在实力上
        this.templateStr = path.resolve(__dirname, 't.html')
    }


    async handleRequest(req, res) {
        let {
            pathname
        } = url.parse(req.url)
        // let absPath = path.join(__dirname, 'public', pathname)
        
        pathname = decodeURIComponent(pathname)
        let absPath = path.join(this.dir, pathname)
   

        try {
            let statObj = await fs.stat(absPath)
         
            if (statObj.isFile()) { //是文件


                // createReadStream(absPath).pipe(res)
                this.sendFile(absPath, req, res, statObj);

            } else { //是文件夹,
                // absPath = path.join('index.html')
                // statObj = await fs.stat(absPath)
                // if (statObj && statObj.isFile) {
                //     this.sendFile(absPath, req, res, statObj);
                // }

                let children = await fs.readdir(absPath)
                
                children = children.map(item => {
                    return {
                        current: item,
                        parent: path.join(pathname, item)
                    }
                })
                    //this.templateStr
                let str = nunjucks.render('/t.html', {
                    items: children,
                })
                console.log(str,"str")
                res.setHeader('COntent-Type', 'text/html;charset=utf-8')
                
                res.end(str)

            }

        } catch (error) {
            console.log(error)
            this.sendError(error, res)
        }




    }

    start() {
        http.createServer(this.handleRequest.bind(this)).listen(this.port, () => {
            console.log("server start success on port " + chalk.green(this.port))
        })
    }

    sendFile(absPath, req, res, statObj) {

        res.setHeader('Content-Type', mime.getType(absPath) + ';charset=utf-8')
        createReadStream(absPath).pipe(res)

    }
    sendError(e, res) {
        res.statusCode = 404
        res.end("NOTFOUND")
    }


}